<?php

namespace app\admin\controller;

use app\common\Esclient;
use app\common\model\AnchorIncomeModel;
use app\common\model\ConfigTagModel;
use app\common\model\ConnectModel;
use app\common\model\AdminModel;
use app\common\model\IpStatsModel;
use app\common\model\LiveCategoryModel;
use app\common\model\LiveCategoryTopModel;
use app\common\model\LiveHistoryModel;
use app\common\model\LiveModel;
use app\common\model\LivePreviewModel;
use app\common\model\LiveNoticeModel;
use app\common\model\LiveStreamVisitHistoryModel;
use app\common\model\FootballTeamModel;
use app\common\model\BasketTeamModel;
use app\common\model\MatchesScheduleModel;
use app\common\model\UserModel;
use app\common\model\ConfigPriModel;
use app\common\model\AnchorFansModel;
use app\common\model\VideoModel;
use app\common\model\ConfigPubModel;
use app\common\model\ActivityBarrageModel;
use app\common\model\ActivityBarrageStatModel;
use app\common\model\RegSourceModel;
use app\common\TXService;
use gogrpc\LiveServer;
use gogrpc\TencentTimServer;
use think\Db;
use think\db\Query;
use think\Exception;
use think\facade\Request;
use think\facade\Cache;
use think\Validate;
use Elasticsearch\ClientBuilder;
use app\common\QcloudSTS;
use stdClass;

class LiveController extends BaseController
{
    public function index()
    {
        $categorys = LiveCategoryModel::where("status", 1)->order('sort', 'asc')->order('id', 'desc')->select();
        return $this->assign([
            'categorys' => $categorys,
            'tags'      => json_encode(ConfigTagModel::getTitleAndPoint()),
            // etype市场专用类型判断，1为市场专用
            'etype'      => Request::get('etype', 0, 'intval'),
        ])->fetch();
    }

    public function dashboard()
    {
        $page  = Request::param('page') ?? 1;
        $limit = 12;
        $where = ['status' => 1];
        $lives = LiveModel::with('anchor')->where($where)->order(['id' => 'desc'])->limit(($page - 1) * $limit, $limit)->select();
        $count = LiveModel::where($where)->count('*');

        $this->assign('lives', $lives);
        $this->assign('page', $page);
        $this->assign('limit', $limit);
        $this->assign('count', $count);
        return $this->fetch();
    }

    public function live_status()
    {
        $page  = Request::param('page') ?? 1;
        $limit  = Request::param('limit') ?? 20;
        $where = ['status' => 1];
        $count = LiveModel::with('anchor')->where($where)->count("id");
        $lives = LiveModel::with('anchor')->where($where)->order(['id' => 'desc'])->limit(($page - 1) * $limit, $limit)->select();
        foreach ($lives as $key => $value) {
            $lives[$key]['start_time'] = date('Y-m-d H:i:s', $value['start_stamp']);
            if ($value['play_from_source'] == 1) {
                $headers = @get_headers($value['pull_url']);
                if ($headers && strpos($headers[0], '200')) {
                    $lives[$key]['stream_status'] = 1;
                } else {
                    $lives[$key]['stream_status'] = 0;
                }
            } else {

                $lives[$key]['stream_status'] = $this->check_stream($value['stream']);
            }
        }
        if (count($lives) > 0) {
            return json(["code" => 0, "msg" => "", "data" => $lives, "count" => $count]);
        }

        return self::bulidFail("未查询到相关数据");
    }

    private function check_stream($stream)
    {
        $sts = new QcloudSTS();
        $configPri = getConfigPri();
        $action = "DescribeLiveStreamOnlineList";
        $Timestamp = time();
        $Nonce = random_int(10000, 20000);
        $inputParams = [];
        $inputParams["SecretId"] = $configPri['qcloud_live_secretid'];
        $inputParams["Timestamp"] = $Timestamp;
        $inputParams["Nonce"] = $Nonce;
        $inputParams["Region"] = $configPri['cos_region'];
        $inputParams["Action"] = $action;
        $inputParams["Version"] = "2018-08-01";
        $inputParams["StreamName"] = $stream;

        $config = [];
        $config["domain"] = "live.tencentcloudapi.com";

        $params = [
            "SecretId" =>   $configPri['qcloud_live_secretid'],
            "Timestamp" =>  $Timestamp,
            "Nonce" =>    $Nonce,
            "Action" =>   $action,
            "Region" =>     $configPri['cos_region'],
            "Version" =>    "2018-08-01",
            "StreamName" => $stream,
        ];

        $inputParams["Signature"] = $sts->getSignature($params, $configPri['qcloud_live_secretkey'], "GET", $config);
        $paramsStr = $sts->json2str($inputParams);
        $resp = file_get_contents("https://" . $config["domain"] . "/?" . $paramsStr);
        $ret = json_decode($resp, true);

        return $ret['Response']['TotalNum'];
    }

    public function tag()
    {
        if (!$id = trim($this->get('id', ''))) {
            return static::bulidFail('主播ID错误');
        }

        if (!$model = UserModel::field('id,nick_name,tags')->where('id', $id)->find()) {
            return static::bulidFail('主播不存在');
        }

        $live = LiveModel::field('tag,anchorid,base_hot, category')->where('anchorid', $id)->find();
        if ($this->request->isAjax()) {

            if (!in_array($tag = trim($this->post('tag', '')), array_merge(array_column(ConfigTagModel::lists(), 'id'), [0]))) {
                return static::bulidFail('你选择标签非法');
            }

            try {

                $tag = ConfigTagModel::get($tag);
                $live->tag = $tag['id'];
                if ($tag->type == 1) {
                    $live->base_hot = $live->base_hot + $tag->point;
                } else {
                    $live->base_hot = $live->base_hot - $tag->point;
                }
                $live->base_hot = $live->base_hot > 0 ? $live->base_hot : 0;
                $r_liveing_key      = "LIVING:" . $live->anchorid;
                $cache_data = redis_get($r_liveing_key);
                if (empty($cache_data)) {
                    return self::bulidFail("修改失败，未找到该直播间缓存数据");
                }

                $cache_data['heat'] = intval($live->base_hot);
                redis_set($r_liveing_key, $cache_data);
                $live_server = new LiveServer();
                $res         = $live_server->UpdateBaseHeat($live->anchorid, $live->base_hot);
                if (!$res) {
                    throw new \Exception('调整标签热度失败.');
                }

                $live->category = 2;

                $live->save();
            } catch (Exception $exception) {
            }

            // $model->tags = $tag;

            // 记录日志
            $log_content = "修改直播标签，主播ID：{$model->id}";
            parent::addAdminLog($log_content, $model->id);
            return static::bulidSuccess();
        }

        return $this->assign([
            'tags'  => ConfigTagModel::getTitleAndPoint(),
            'live' => $live,
            'model' => $model->toArray(),
        ])->fetch();
    }

    public function add()
    {
        $categorys = LiveCategoryModel::where("status", 1)->order('sort', 'asc')->order('id', 'desc')->select();
        $this->assign('categorys', $categorys);
        return $this->fetch();
    }

    public function linkmatch_post()
    {
        if (LiveModel::where(['liveid' => Request::param('id')])->update(['matchid' => Request::param('matchid')])) {
            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function logs()
    {
        $categorys = LiveCategoryModel::where("status", 1)->order('sort', 'asc')->order('id', 'desc')->select();
        $this->assign('categorys', $categorys);
        return $this->fetch();
    }

    public function category()
    {
        return $this->fetch();
    }

    public function category_add()
    {
        return $this->assign('top_cate', LiveCategoryTopModel::getTopCate())->fetch();
    }

    public function category_edit()
    {
        $id       = Request::param('id');
        $category = LiveCategoryModel::get($id);
        if (!$category) {
            $this->redirect('/admin/live/index');
        }

        $top_cate = LiveCategoryTopModel::getTopCate();
        $this->assign('top_cate', $top_cate);
        $this->assign('category', $category);
        return $this->fetch();
    }

    public function getcategorys()
    {
        $categorys = LiveCategoryModel::with('categoryTop')->order('sort asc,id desc')->select();

        if (count($categorys) < 1) {
            return self::bulidFail("未查询到相关数据");
        }

        return self::bulidSuccess($categorys);
    }

    public function category_add_post()
    {
        $category = new LiveCategoryModel(Request::param());
        if ($category->save()) {
            // 记录日志
            $log_content = "添加直播分类，名称：{$category->title}，ID：{$category->id}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function category_edit_post()
    {
        $id       = Request::param('id');
        $category = LiveCategoryModel::get($id);
        if ($category->save(Request::except('id'))) {
            // 记录日志
            $log_content = "修改直播分类，名称：{$category->title}，ID：{$category->id}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function category_hide_post()
    {
        $id       = Request::param('id');
        $category = LiveCategoryModel::get($id);
        if (!$category) {
            return self::bulidFail('未查询到相关分类');
        }

        if (LiveCategoryModel::update(['status' => 0], ['id' => Request::param('id')])) {
            // 记录日志
            $log_content = "设置隐藏直播分类，名称：{$category->title}，ID：{$category->id}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function category_show_post()
    {
        $id       = Request::param('id');
        $category = LiveCategoryModel::get($id);
        if (!$category) {
            return self::bulidFail('未查询到相关分类');
        }

        if (LiveCategoryModel::update(['status' => 1], ['id' => Request::param('id')])) {
            // 记录日志
            $log_content = "设置显示直播分类，名称：{$category->title}，ID：{$category->id}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }


    /**
     * 顶级分类
     * @return mixed
     */
    public function category_top()
    {
        return $this->fetch();
    }

    public function category_top_add()
    {
        return $this->fetch();
    }

    public function category_top_edit()
    {
        $id       = Request::param('id');
        $category = LiveCategoryTopModel::get($id);
        if (!$category) {
            $this->redirect(url('live/category_top'));
        }

        $this->assign('category', $category);
        return $this->fetch();
    }

    public function getcategorytop()
    {
        $categorys = LiveCategoryTopModel::order('sort', 'asc')->order('id', 'desc')->select();

        if (count($categorys) < 1) {
            return self::bulidFail("未查询到相关数据");
        }

        return self::bulidSuccess($categorys);
    }

    public function category_top_add_post()
    {
        $title = Request::param('title');
        // 查询是否有相同名称的分类
        $where['title'] = $title;
        $title_exists   = LiveCategoryTopModel::where($where)->count();
        if ($title_exists > 0) {
            return self::bulidFail("该分类名称已经存在");
        }

        $category = new LiveCategoryTopModel(Request::param());
        if ($category->save()) {
            // 记录日志
            $log_content = "添加直播顶级分类，名称：{$category->title}，ID：{$category->id}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function category_top_edit_post()
    {
        $id       = Request::param('id');
        $title    = Request::param('title');
        $category = LiveCategoryTopModel::get($id);
        if (empty($category)) {
            return self::bulidFail("分类信息不存在");
        }


        // 查询是否有相同名称的分类
        $where[]      = ['id', '<>', $id];
        $where[]      = ['title', '=', $title];
        $title_exists = LiveCategoryTopModel::where($where)->count();
        if ($title_exists > 0) {
            return self::bulidFail("该分类名称已经存在");
        }

        if ($category->save(Request::except('id'))) {
            // 记录日志
            $log_content = "修改直播顶级分类，名称：{$category->title}，ID：{$category->id}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function category_top_hide_post()
    {
        $id       = Request::param('id');
        $category = LiveCategoryTopModel::get($id);
        if (!$category) {
            return self::bulidFail('未查询到相关分类');
        }

        redis_del("live_category_top_list");
        if (LiveCategoryTopModel::update(['status' => 0], ['id' => Request::param('id')])) {
            // 记录日志
            $log_content = "设置隐藏直播顶级分类，名称：{$category->title}，ID：{$category->id}";
            parent::addAdminLog($log_content);
            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function category_top_show_post()
    {
        $id       = Request::param('id');
        $category = LiveCategoryTopModel::get($id);
        if (!$category) {
            return self::bulidFail('未查询到相关分类');
        }
        
        redis_del("live_category_top_list");
        if (LiveCategoryTopModel::update(['status' => 1], ['id' => Request::param('id')])) {
            // 记录日志
            $log_content = "设置显示直播顶级分类，名称：{$category->title}，ID：{$category->id}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    private static function avg_duration($liveid)
    {
        if ($liveid == '') {
            return 0;
        }
        $params = [
            'index' => 'es_live_room_data',

            'where' => [
                ['live_id', '=', $liveid]
            ],

            'body' => [
                'size' => 0,
                'aggs' => [
                    'total_sum' => [
                        'sum' => [
                            'field' => 'duration'
                        ]
                    ]
                ]
            ]

        ];
        $list = (new Esclient())->sum($params);
        if ($list['total'] == 0) {
            return 0;
        }
        return (intval($list['sum'] / $list['total'] / 60)) . '分' . (intval($list['sum'] / $list['total']) % 60) . '秒';
    }

    public function user_duration()
    {
        $liveid = $this->get('liveid');
        // test
        // $liveid = 169113464324;
        $summary = [
            'range_1' => 0,
            'range_5' => 0,
            'range_10' => 0,
            'range_30' => 0,
            'range_60' => 0,
            'more' => 0,
        ];

        if ($liveid == 0) {
            return self::bulidFail("直播id异常");
        }

        // summary
        $where = [
            'index' => 'es_live_room_data',
            'where' => [
                ['live_id', '=', $liveid],
                ['duration', '<=', 60],
            ],
        ];

        $resp = (new Esclient())->search($where);
        $summary['range_1'] = $resp['total'];

        $where = [
            'index' => 'es_live_room_data',
            'where' => [
                ['live_id', '=', $liveid],
                ['duration', '>=', 60],
                ['duration', '<', 300],
            ],
        ];

        $resp = (new Esclient())->search($where);
        $summary['range_5'] = $resp['total'];

        $where = [
            'index' => 'es_live_room_data',
            'where' => [
                ['live_id', '=', $liveid],
                ['duration', '>=', 300],
                ['duration', '<', 600],
            ],
        ];

        $resp = (new Esclient())->search($where);
        $summary['range_10'] = $resp['total'];

        $where = [
            'index' => 'es_live_room_data',
            'where' => [
                ['live_id', '=', $liveid],
                ['duration', '>=', 600],
                ['duration', '<', 1800],
            ],
        ];

        $resp = (new Esclient())->search($where);
        $summary['range_30'] = $resp['total'];

        $where = [
            'index' => 'es_live_room_data',
            'where' => [
                ['live_id', '=', $liveid],
                ['duration', '>=', 1800],
                ['duration', '<', 3600],
            ],
        ];

        $resp = (new Esclient())->search($where);
        $summary['range_60'] = $resp['total'];

        $where = [
            'index' => 'es_live_room_data',
            'where' => [
                ['live_id', '=', $liveid],
                ['duration', '>=', 3600],
            ],
        ];

        $resp = (new Esclient())->search($where);
        $summary['more'] = $resp['total'];
        return $this->assign([
            'liveid' => $liveid,
            'summary' => $summary,
        ])->fetch();
    }

    public function ajax_user_duration()
    {
        $liveid = $this->get('liveid');
        // test
        // $liveid = 169113464324;

        $size = $this->get("size");
        $page = (int)$this->get('page', 1);

        $condition = [];
        $condition[] = ['live_id', '=', $liveid];

        $uid = intval($this->get("uid"));
        $nickname = $this->get("nickname");
        $account = $this->get('account');
        $s_duration = $this->get('s_duration');
        $e_duration = $this->get('e_duration');

        $fromdb = [];
        if ($uid > 0) {
            $fromdb[] = ['id', '=', $uid];
        }
        if ($nickname != '') {
            $fromdb[] = ['nick_name', 'like', '%' . $nickname . '%'];
        }
        if ($account != '') {
            $fromdb[] = ['account', 'like', '%' . $account . '%'];
        }
        if (!empty($fromdb)) {
            $find_user = UserModel::where($fromdb)->find();
            if (!empty($find_user)) {
                $condition[] = ['uid', '=', $find_user['id']];
            } else {
                return self::bulidFail("未注册用户");
            }
        }

        if (intval($s_duration) > 0) {
            $condition[] = ['duration', '>=', $s_duration * 60];
        }

        if (intval($e_duration) > 0) {
            $condition[] = ['duration', '<=', $e_duration * 60];
        }

        // var_dump($condition);

        $where = [
            'index' => 'es_live_room_data',
            'size' => $limit = (int)$this->get('limit', $size),
            'from' => ($page - 1) * $limit,
            'where' => $condition,
            'sort' => ['duration' => 'desc']
        ];

        $list = (new Esclient())->search($where);
        if ($list['total'] > 0) {
            // 组合用户数据
            $user_ids = [];
            foreach ($list['data'] as $key => $value) {
                $user_ids[] = $value['uid'];
            }
            $ids = implode(',', $user_ids);
            $where = [];
            $where['id'] = ['in', $user_ids];
            $users = UserModel::where('id', 'in', $ids)->limit(($page - 1) * $size, $size)->select();

            $login_platform = [
                0 => 'WEB',
                1 => 'iOS',
                2 => 'Android',
                3 => 'H5'
            ];
            foreach ($list['data'] as $key => $value) {
                $list['data'][$key]['login_platform'] = isset($value['platform']) ? $login_platform[$value['platform']] : $login_platform[0];

                // 登录用户
                foreach ($users as $uk => $uv) {
                    if ($value['uid'] == $uv['id']) {
                        $list['data'][$key]['account'] = $uv['account'];
                        $list['data'][$key]['nick_name'] = $uv['nick_name'];
                        $list['data'][$key]['login_platform'] = isset($value['platform']) ? $login_platform[$value['platform']] : $login_platform[0];
                        $list['data'][$key]['last_login'] = $uv['last_login'];
                        $list['data'][$key]['regist_time'] = $uv['regist_time'];
                    }
                    if ($value['duration'] < 60) {
                        $list[$key]['duration'] = '<1';
                    }
                }
            }

            $ret['list'] = $list['data'];

            return json(["code" => 0, "msg" => "", "data" => $list['data'], "count" => $list['total']]);
        }

        return self::bulidFail("未查询到相关数据");
    }
    /**
     * 获取直播列表数据
     * @return \think\response\Json
     */
    public function getlives()
    {
        $model = new LiveModel();
        if ($anchorid = $this->get('anchorid')) {
            $model = $model->where('anchorid', $anchorid);
        }
        if ($categoryid = $this->get('categoryid')) {
            $model = $model->where('categoryid', $categoryid);
        }

        $cache = Cache::store('redis')->handler();
        $lives = $model->with([
            'anchor'   => function (Query $query) {
                $query->field('id, nick_name');
            },
            'matches'  => function (Query $query) {
                $query->field('match_id, comp,home,away');
            },
            'category' => function (Query $query) {
                $query->field('id, title');
            }
        ])->page($this->get('page', 1), $this->get('limit', 20))
            ->order("id", "desc")
            ->select()->each(function ($query) use ($cache) {
                if ($query->start_stamp > 0) {
                    $query->start_stamp = date('Y-m-d H:i:s', $query->start_stamp);
                }
                // 实时热度值
                $query->hot             = $cache->hGet("statisticsGroup_" . $query->anchorid, 'hot');
                $query->hot             = $query->hot > 0 ? $query->hot : $query->base_hot;
                $query->active_viewer   = $cache->hGet("statisticsGroup_" . $query->anchorid, 'active_viewer') ?: 0;
                $query->unique_ip_count = $cache->hGet("statisticsGroup_" . $query->anchorid, 'unique_ip_count') ?: 0;
                $query->high_count      = $cache->hGet("statisticsGroup_" . $query->anchorid, 'barrage_time_count') ?: 0;
                $query->avg_duration = self::avg_duration($query->liveid);
            })->toArray();

        $viewer_count = $this->get_source_count();

        return json([
            "count"    => $model->count('id'),
            "data"     => $lives,
            'ip_total' => $cache->get('global_ip_count:' . date('Ymd')) ?: 0,
            "viewer_count" => $viewer_count->sum,
            "code"     => 0,
            "msg"      => "",
        ]);
    }

    public function getlogs()
    {
        $anchorid   = Request::param("anchorid");
        $categoryid = Request::param("categoryid");
        $liveid     = Request::param("liveid");
        $where      = [];
        if ($anchorid) {
            $where["anchorid"] = $anchorid;
        }
        if ($categoryid) {
            $where["categoryid"] = $categoryid;
        }
        if ($liveid) {
            $where["liveid"] = $liveid;
        }

        $page  = Request::param("page");
        $limit = Request::param("limit");

        $logs = LiveHistoryModel::where($where)->with(['anchor' => function ($query) {
            $query->field('id, nick_name');
        }, 'category'])->limit(($page - 1) * $limit, $limit)->order("start_time", "desc")->select();

        if (count($logs) > 0) {
            $count = LiveHistoryModel::where($where)->count("id");
            return json(["code" => 0, "msg" => "", "data" => $logs, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    // 联赛信息
    public function match_event()
    {
        $sport_id = Request::param("sport_id");

        if ($sport_id < 1) {
            return self::bulidFail("未查询到相关数据");
        }

        $where = [];
        if ($sport_id == 3) {
            $where[] = ['sport_id', 'in', [101, 102, 103]];
        } else {
            $where[] = ['sport_id', '=', $sport_id];
        }
        $where[] = ['match_status', 'in', [1, 2]];
        $where[] = ['match_time', '>=', time() - 14400];
        $where[] = ['match_time', '<=', strtotime(date('Y-m-d 23:59:59', time() + 60 * 60 * 48),)];

        $field = 'id,match_id,match_time,home,away';
        $list  = MatchesScheduleModel::where($where)->field($field)->select();

        if (empty($list)) {
            return self::bulidFail("未查询到相关数据");
        }

        foreach ($list as &$item) {
            $item->match_time_str = date('Y-m-d H:i:s', $item->match_time);
        }

        return self::bulidSuccess($list);
    }

    public function match_list()
    {
        // echo $sport_id = Request::param("sport_id"); // 1-足球，2-篮球 3-网球
        $competition_id = Request::param("competition_id");

        $matches = [];
        $today   = strtotime(date("Y-m-d") . " 00:00:00");

        $sql     = "select db_basket_match.id, db_basket_match.competition_id, db_basket_match.status, db_basket_match.time, db_basket_match.home_id, db_basket_match.home_score, db_basket_match.away_id, db_basket_match.away_score, db_matches.pushurl1, db_matches.sport_id from db_basket_match 
                    join db_matches on db_matches.match_id=db_basket_match.id 
                    where match_time>={$today} and status<10 and db_matches.pushurl1<>'' and competition_id={$competition_id}
                    union 
                    select db_football_match.id, db_football_match.competition_id, db_football_match.status, db_football_match.time, db_football_match.home_id, db_football_match.home_score, db_football_match.away_id, db_football_match.away_score, db_matches.pushurl1, db_matches.sport_id from db_football_match 
                    join db_matches on db_matches.match_id=db_football_match.id 
                    where match_time>={$today} and status<8 and db_matches.pushurl1<>'' and competition_id={$competition_id}
                    ";
        $matches = Db::query($sql);
        // if (intval($sport_id) == 1) {
        //     $matches = MatchesModel::alias('M')
        //         ->leftJoin('db_football_match', 'M.match_id = db_football_match.id')
        //         ->field('db_football_match.*, M.pushurl1, M.pushurl2, M.pushurl3')
        //         ->where("db_football_match.status", "<", 8)
        //         ->where("time", ">", $time)
        //         ->order(['time' => 'asc'])
        //         ->select();


        if (!empty($matches)) {
            foreach ($matches as $key => $value) {
                if ($value["sport_id"] == 1) {
                    $matches[$key]['home_team'] = FootballTeamModel::where("id", $value["home_id"])->find()["name_zh"];
                    $matches[$key]['away_team'] = FootballTeamModel::where("id", $value["away_id"])->find()["name_zh"];
                }

                if ($value["sport_id"] == 2) {
                    $matches[$key]['home_team'] = BasketTeamModel::where("id", $value["home_id"])->find()["name_zh"];
                    $matches[$key]['away_team'] = BasketTeamModel::where("id", $value["away_id"])->find()["name_zh"];
                }
            }
            return self::bulidSuccess($matches);
        }
        // }

        // if (intval($sport_id) == 2) {
        //     $matches = MatchesModel::alias('M')
        //         ->leftJoin('db_basket_match', 'M.match_id = db_basket_match.id')
        //         ->field('db_basket_match.*, M.pushurl1, M.pushurl2, M.pushurl3')
        //         ->where("db_basket_match.status", "<", 8)
        //         ->where("time", ">", $time)
        //         ->order(['time' => 'asc'])
        //         ->select();

        //     foreach ($matches as $key => $value) {
        //         $matches[$key]['home_team'] = BasketTeamModel::where("id", $value["home_id"])->find()["name_zh"];
        //         $matches[$key]['away_team'] = BasketTeamModel::where("id", $value["away_id"])->find()["name_zh"];
        //     }

        //     return self::bulidSuccess($matches);
        // }

        return self::bulidFail("未查询到相关数据");
    }

    public function add_post()
    {
        $all_param = Request::param();
        $validate = new Validate([
            // 'title'    => 'require|length:1,50',
            'anchorid' => 'require|number',
            'pull_url' => 'require',
        ], [
            // "title"            => "直播标题在1-50个字符",
            "anchorid.require" => "主播ID必填",
            "anchorid.number"  => "请填写正确的主播id，主播id通常为数字",
            "pull_url"         => "播流地址必填",
        ]);

        if (!$validate->check($all_param)) {
            return self::bulidFail($validate->getError());
        }

        $live = new LiveModel($all_param);

        // $pathinfo = pathinfo($all_param['pull_url']);
        // if (isset($pathinfo['extension']) && ((!strpos(strtolower($pathinfo['extension']), 'mp4') || !strpos(strtolower($pathinfo['extension']), 'm3u8')))) {
        //     if ($all_param['play_from_source'] == 1) {
        //         $live->reply_video = 1;
        //     }
        // }

        // 后台开播固定原地址播放
        $live->reply_video = 1;
        $live->play_from_source = 1;

        // 强制将flv格式设置为直播流
        if (strpos(strtolower($all_param['pull_url']), 'flv')) {
            // $live->reply_video = 0;
            return self::bulidFail('不支持FLV视频格式,媒体流播放只支持(m3u8, mp4)');
        }

        // 是否认证
        $user = UserModel::where(['id' => $live->anchorid])->find();
        if (empty($user)) {
            return self::bulidFail('用户信息不存在');
        }
        if ($user["is_anchor"] != 1) {
            return self::bulidFail('该用户未通过认证');
        }

        $livecheck = LiveModel::where(['anchorid' => $live->anchorid])->find();
        if ($livecheck) {
            return self::bulidFail('主播已在直播中');
        }

        // 查询所属分类
        $live_category = LiveCategoryModel::get($live->categoryid);
        if (!$live_category) {
            return self::bulidFail('分类信息错误');
        }

        $config_pri = ConfigPriModel::get(1);
        $heat       = 0;
        if ($config_pri) {
            $heat = mt_rand($config_pri->baseheats_start, $config_pri->baseheats_end);
        }

        $live->status       = 1;
        $live->category     = $live_category->category;
        $live->start_stamp  = time();
        $live->rec_switch   = ($live->rec_switch ?? 0) == 'on' ? 1 : 0;
        $live->liveid       = time() . substr(strval($live->anchorid), 4, 4);
        $live->platform     = 3;

        if ($user->tags > 0) {
            $tag = ConfigTagModel::get($user->tags);
            if ($tag) {
                $live->tag = $tag['id'];

                if ($tag->type == 1) {
                    $heat = $heat + $tag->point;
                } else {
                    $heat = $heat - $tag->point;
                }
            }
        }

        $live->base_hot     = $heat > 0 ? $heat : 0;
        $live->pull_flv_url = $live->pull_url;
        $type               = explode('.', $live->pull_url);

        switch (end($type)) {
            case "m3u8":
                $live->type = "hls";
                break;
            case "mpd":
                $live->type = "dash";
                break;
            case "flv":
                $live->type = "flv";
                break;
            case "mp4":
                $live->type = "auto";
                break;
            default:
                $live->type = null;
                break;
        }

        $stream_id = explode('/', $live->pull_url);

        $stream_id = explode('.', end($stream_id));

        $live->stream = $stream_id[0];

        $anchor = UserModel::where(['id' => $live->anchorid])->find();
        if (!$anchor) {
            return self::bulidFail('主播ID有误');
        }
        if ($live->stream == "") {
            // $live->stream = $anchor->anchor_secret;
        }
        $live->anchor_name   = $anchor->nick_name;
        $live->anchor_avatar = $anchor->avatar;
        $live->rec_weight    = $anchor->rec_weight;

        // 创建用户
        $res_import = TXService::importAccount($live->anchorid, $user->nick_name, $user->avatar);
        if (!$res_import['status']) {
            return self::bulidFail('直播群组导入用户创建失败:' . $res_import['msg']);
        }

        // 创建群组
        $res_create_room = TXService::createChatRoom($live->anchorid, $live->anchorid);
        if (!$res_create_room['status']) {
            return self::bulidFail('直播群组创建失败:' . $res_create_room['msg']);
        }

        if ($live->save()) {
            // 写入redis
            $rkey = "LIVING:" . $live->anchorid;
            $r    = [
                "anchorid"      => intval($live->anchorid),
                "liveid"        => intval($live->liveid),
                "start"         => date("Y-m-d H:i:s", $live->start_stamp),
                "status"        => 1,
                "matchid"       => intval($live->matchid),
                "nickname"      => "{$live->anchor_name}",
                "heat"          => $live->base_hot,
                "official_type" => 0
            ];

            Cache::store('redis')->set($rkey, json_encode($r), 0);

            // 记录日志
            $log_content = "创建直播，ID:{$live->id}，主播ID:{$live->anchorid}，直播ID:{$live->liveid}";
            parent::addAdminLog($log_content, $live->anchorid);

            return self::echoSuccess($live);
        }
        return self::bulidFail();
    }

    public function stop_post()
    {
        $liveid = Request::param('liveid', 0, 'intval');
        $live   = LiveModel::where(['liveid' => $liveid])->find();
        if (empty($live)) {
            return self::bulidFail('没有相关直播信息');
        }

        $live_server = new LiveServer();
        $res         = $live_server->endLive($live->anchorid);
        if ($res) {
            // 记录日志
            $log_content = "设置主播({$live->anchorid})，直播间({$liveid})停播";
            parent::addAdminLog($log_content, $live->anchorid);
            return parent::bulidSuccess();
        }
        return self::bulidFail("停播操作失败");
    }


    public function signForVod()
    {
        $configPri = getConfigPri();
        // 确定签名的当前时间和失效时间
        $current = time();
        $expired = $current + 86400;  // 签名有效期：1天

        // 向参数列表填入参数
        $arg_list = array(
            "secretId"         => $configPri['qcloud_secretid'],
            "currentTimeStamp" => $current,
            "expireTime"       => $expired,
            "random"           => rand(),
            "oneTimeValid"     => 1
        );

        // 计算签名
        $orignal   = http_build_query($arg_list);
        $signature = base64_encode(hash_hmac('SHA1', $orignal, $configPri['qcloud_secretkey'], true) . $orignal);
        return self::bulidSuccess(['sign' => $signature]);
    }

    public function visit_history()
    {
        return $this->fetch();
    }

    public function getlivestreamvisithistory()
    {
        $userid = Request::param("userid");
        $where  = [];

        $page  = Request::param("page");
        $limit = Request::param("limit");

        $logs =
            Db::query("select lsvh.id, title, liveid, last_visit_time, anchor.nick_name AS anchor_name, user.nick_name AS user_name
        from live_stream_visit_history lsvh
        left join db_user anchor on lsvh.anchorid = anchor.id
        left join db_user user on lsvh.user_id = user.id");
        /*
        LiveStreamVisitHistoryModel::where($where)
        ->join('db_user', 'live_stream_visit_history.anchorid = db_user.id', 'LEFT')
        ->limit(($page-1)*$limit,$limit)->order("last_visit_time","desc")
        ->field("title, liveid, last_visit_time, db_user.nick_name")
        ->select();
*/
        if (count($logs) > 0) {
            $count = LiveStreamVisitHistoryModel::where($where)->count("id");
            return json(["code" => 0, "msg" => "", "data" => $logs, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }


    public function heat_edit()
    {
        $id        = Request::param("id");
        $live_info = LiveModel::where('anchorid', $id)->find();
        if (!$live_info) {
            return $this->error('未查询到相关数据');
        }
        return view("heat_edit", [
            "data" => $live_info->base_hot,
            "id"   => $id,
        ]);
    }

    public function hot_edit_post()
    {

        {
            $id   = Request::param("id");
            $heat = Request::param("heat");
            if (!preg_match("/^\d+$/", $heat)) {
                return self::bulidFail("热度值必须为整数");
            }

            $data = LiveModel::where('anchorid', "=", $id)->field('id,anchorid,liveid,base_hot,hot')->find();
            if (!$data) {
                return self::bulidFail("未找到该直播间");
            }

            // 基础热度
            $old_base_hot = $data->base_hot;

            if($heat<$old_base_hot){
                return self::bulidFail("当前热度不能小于基础热度");
            }

            $data->hot = abs($heat-$old_base_hot);

            $cache = Cache::store('redis')->handler();
//            $cache_data = $cache->hGet("statisticsGroup_" . $data->anchorid, 'hot');
//            if (empty($cache_data)) {
//                return self::bulidFail("修改失败，未找到该直播间缓存数据");
//            }

            Db::startTrans();
            LiveModel::startTrans();
            try {
                if (!$data->save()) {
                    throw new \Exception('调整失败');
                }

                // 记录表日志
                $log_content = "调整当前热度，主播ID:{$data->anchorid}，直播ID:{$data->liveid}，调整前：{$data->hot}，调整后:{$heat}";
                if (parent::addAdminLog($log_content, $data->anchorid) < 1) {
                    throw new \Exception('日志插入失败');
                }

                $cache->hSet("statisticsGroup_" . $data->anchorid, 'hot', intval($heat));


                Db::commit();
                LiveModel::commit();
                return self::bulidSuccess([], '调整当前热度成功');
            } catch (\Exception $e) {
                Db::rollback();
                LiveModel::rollback();
                return self::bulidDataFail(['error' => $e->getMessage()], '调整失败');
            }
            return self::bulidFail('调整失败');
        }


    }


    public function heat_edit_post()
    {
        $id   = Request::param("id");
        $heat = Request::param("heat");
        if (!preg_match("/^\d+$/", $heat)) {
            return self::bulidFail("热度值必须为整数");
        }

        $data = LiveModel::where('anchorid', "=", $id)->field('id,anchorid,liveid,base_hot')->find();
        if (!$data) {
            return self::bulidFail("未找到该直播间");
        }
        // 基础热度
        $old_base_hot = $data->base_hot;
        $data->base_hot = $heat;

        $r_liveing_key      = "LIVING:" . $id;
        $cache_data = redis_get($r_liveing_key);
        if (empty($cache_data)) {
            return self::bulidFail("修改失败，未找到该直播间缓存数据");
        }

        Db::startTrans();
        LiveModel::startTrans();
        try {
            if (!$data->save()) {
                throw new \Exception('调整失败');
            }

            // 记录表日志
            $log_content = "调整基础热度，主播ID:{$data->anchorid}，直播ID:{$data->liveid}，基础热度:{$heat}";
            if (parent::addAdminLog($log_content, $data->anchorid) < 1) {
                throw new \Exception('日志插入失败');
            }

            $cache_data['heat'] = intval($heat);
            redis_set($r_liveing_key, $cache_data);


            $live_server = new LiveServer();
            $res         = $live_server->UpdateBaseHeat($data->anchorid, $heat);
            if (!$res) {
                throw new \Exception('调整失败.');
            }

            Db::commit();
            LiveModel::commit();
            return self::bulidSuccess([], '调整基础热度成功');
        } catch (\Exception $e) {
            Db::rollback();
            LiveModel::rollback();
            // 修改错误还原
            $cache_data['heat'] = intval($old_base_hot);
            redis_set($r_liveing_key, $cache_data);

            return self::bulidDataFail(['error' => $e->getMessage()], '调整失败');
        }
        return self::bulidFail('调整失败');
    }


    // public function getHeat($anchorid)
    // {
    //     $rkey      = "LIVING:" . $anchorid;
    //     $cacheData = Cache::store('redis')->get($rkey);
    //     $cacheData = json_decode($cacheData, true);
    //     return isset($cacheData['heat']) ? $cacheData['heat'] : 0;
    // }


    /**
     * 修改直播信息
     * @return \think\response\Json|\think\response\View
     */
    public function edit()
    {
        $id   = Request::param("id");
        $info = LiveModel::where('anchorid', "=", $id)->find();
        if (empty($info)) {
            return self::bulidFail("直播信息不存在");
        }

        if (Request::isPost()) {
            $all_request = Request::param();
            $validate    = new Validate([
                'title'  => 'require|length:1,50',
                'thumb'  => 'require|pass:/http[s]?:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is',
                'status' => "require|number|in:0,1,2",
            ], [
                "title"  => "直播标题在1-50个字符",
                "thumb"  => "请正确上传封面图",
                "status" => "请正确选择状态",
            ]);

            if (!$validate->check($all_request)) {
                return self::bulidFail($validate->getError());
            }

            if ($all_request['status'] != $info->status) {
                $info->status = $all_request['status'];
            }

            $info->title = $all_request['title'];
            $info->thumb = $all_request['thumb'];
            $info->play_from_source = $all_request['play_from_source'];
            $info->watermark_position = $all_request['watermark_position'];


            if (!$info->reply_video) {
                $info->enable_webrtc = $all_request['enable_webrtc'];
            }

            if ($info->save()) {
                if ($all_request['status'] != $info->status) {
                    $r_key      = "LIVING:" . $id;
                    $cache_data = Cache::store('redis')->get($r_key);
                    $cache_data = json_decode($cache_data, true);
                    if ($cache_data) {
                        $cache_data['status'] = intval($info->status);
                        Cache::store('redis')->set($r_key, json_encode($cache_data), 0);
                    }
                }

                // 记录日志
                $log_content = "修改直播信息，ID:{$info->id}，主播ID:{$info->anchorid}，直播ID:{$info->liveid}";
                parent::addAdminLog($log_content, $info->anchorid);

                return self::bulidSuccess([], "修改成功");
            }

            return self::bulidFail("修改失败");
        }

        return view("edit", [
            "data" => $info,
            "id"   => $id,
        ]);
    }


    public function official_type()
    {
        $id   = Request::param("id");
        $type = intval(Request::param("type"));
        if (LiveModel::where(['anchorid' => $id])->update(['official_type' => $type])) {
            return self::bulidSuccess();
        }

        return self::bulidFail("操作失败");
    }

    //公告列表
    public function visit_notice()
    {
        return $this->fetch("notice_list");
    }

    public function notice_list()
    {
        $name      = Request::param("name");
        $type      = Request::param("type", -1);
        $anchorid  = Request::param("anchorid");
        $startTime = Request::param("start_time");
        $endTime   = Request::param("end_time");
        $page      = Request::param("page");
        $limit     = Request::param("limit");
        $offse     = ($page - 1) >= 0 ? ($page - 1) * $limit : 0;
        $where     = [];
        $query     = LiveNoticeModel::field("*");
        if ($startTime) {
            $query->where('create_time', '>=', $startTime);
        }
        if ($endTime) {
            if (strtotime($startTime) >= strtotime($endTime)) {
                return self::bulidFail("开始时间必须小于结束时间");
            }
            $query->where('create_time', '<', $endTime);
        }
        if (is_numeric($type) && $type >= 0) {
            $query->where('type', $type);
        }
        if ($anchorid) {
            $query->where('anchorid', $anchorid);
        }

        if ($name) {
            $adminId = AdminModel::where(['account' => $name])->value('id');
            if ($adminId) {
                $query->where(['manager_id' => $adminId]);
            } else {
                return self::bulidFail($name . "用户不存在");
            }
        }
        $list = $query->with('admin')->order("id", "desc")->limit($offse, $limit)->select();
        if (count($list) > 0) {
            $count = LiveNoticeModel::where($where)->count("id");

            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function notice_add()
    {
        return $this->fetch("nocitce_add");
    }

    public function notice_add_post()
    {
        $params                = Request::param();
        $params['create_time'] = nowFormat();
        $params['manager_id']  = $this->userinfo->id;
        $model                 = new LiveNoticeModel($params);

        if ($model->save()) {
            // 记录日志
            $log_content = "添加了房间公告，ID:" . $model->id . (isset($model->anchorid) ? '，uid:' . $model->anchorid : '');
            parent::addAdminLog($log_content, isset($model->anchorid) ? $model->anchorid : 0);
            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function notice_edit()
    {
        $id = Request::get('id');
        if ($id < 1) {
            return self::bulidFail();
        }
        $info = LiveNoticeModel::get($id);
        $this->assign('info', $info);
        return $this->fetch("nocitce_edit");
    }

    public function notice_edit_post()
    {
        $id           = Request::param('id');
        $notice_model = LiveNoticeModel::get($id);
        if ($notice_model->save(Request::except('id'))) {
            // 记录日志
            $log_content = "修改了房间公告，ID:" . $id . ($notice_model->anchorid > 0 ? '，uid:' . $notice_model->anchorid : '');
            parent::addAdminLog($log_content, $notice_model->anchorid);
            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    /**
     * 单个主播直播间公告修改
     * @return \think\response\Json
     */
    public function anchor_room_notice_edit()
    {
        return self::bulidFail('没有相关操作');
        $anchor_id = Request::param('anchorid');
        $content   = Request::param('content');

        $validate = new Validate([
            'anchorid' => 'require|number',
            'content'  => 'require|max:200',
        ], [
            "anchorid.require" => "参数错误",
            "anchorid.number"  => "参数错误",
            "content.require"  => "请输入公告内容",
            "content.max"      => "公告内容最多200字",
        ]);
        if (!$validate->check(Request::param())) {
            return self::bulidFail($validate->getError());
        }

        $live_info = LiveNoticeModel::where('anchorid', $anchor_id)->find();
        if ($live_info) {
            $live_info->content = $content;
        } else {
            $data      = [
                'type'        => 1,
                'anchorid'    => $anchor_id,
                'content'     => $content,
                'manager_id'  => $this->userinfo->id,
                'create_time' => nowFormat()
            ];
            $live_info = new LiveNoticeModel($data);
        }

        if ($live_info->save()) {
            // 记录日志
            $log_content = "修改了主播({$anchor_id})房间公告";
            parent::addAdminLog($log_content, $anchor_id);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    /**
     * 直播间公告删除
     * @return \think\response\Json
     */
    public function notice_del_post()
    {
        $id             = Request::param('id');
        $notice_info = LiveNoticeModel::get($id);
        if (!$notice_info) {
            return self::bulidFail("公告信息不存在");
        }

        if (LiveNoticeModel::destroy($id)) {
            // 记录日志
            $log_content = "删除直播间公告，ID：{$notice_info->id}，内容：{$notice_info->content}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }


    /**
     * 历史直播
     * @return \think\response\Json
     */

    public function history()
    {
        return $this->fetch();
    }

    public function get_history()
    {
        $anchor_id = Request::param("anchorid");
        $nick_name = Request::param("nick_name");
        $start_time = Request::param("start_time");
        $end_time = Request::param("end_time");
        $match_start_time = Request::param("match_start_time");
        $match_end_time = Request::param("match_end_time");
        $page      = Request::param("page");
        $limit     = Request::param("limit");
        $live_type = Request::param("live_type");

        $where = [];

        if ($anchor_id) {
            $where[] = ['anchorid', '=', is_numeric($anchor_id) ? $anchor_id : 0];
        }

        if (mb_strlen($nick_name) > 0) {
            $u_where[] = ['nick_name', 'like', "%{$nick_name}%"];
            $uid_arr   = UserModel::where($u_where)->column('id');
            $where[]   = ['anchorid', 'in', $uid_arr];
        }

        if ($start_time != '') {
            $start_time = strtotime($start_time);
            $where[] = ['start_stamp', '>=', $start_time];
        }

        if ($end_time != '') {
            $end_time = strtotime($end_time);
            $where[] = ['end_stamp', '<=', $end_time];
        }

        if ($match_start_time != '') {
            $match_start_time = strtotime($match_start_time);
            $where[] = ['match_start_time', '>=', $match_start_time];
        }
        if ($match_end_time != '') {
            $match_end_time = strtotime($match_end_time);
            $where[] = ['match_end_time', '<=', $match_end_time];
        }

        if ($live_type == 1) {
            $where[] = ['platform', '<>', 3];
        }
        if ($live_type == 2) {
            $where[] = ['platform', '=', 3];
            $where[] = ['anchorid', 'not in', LiveModel::auto_live_ids()];
        }
        if ($live_type == 3) {
            $where[] = ['anchorid', 'in', LiveModel::auto_live_ids()];
        }

        $list = LiveHistoryModel::with([
            'anchor'   => function ($query) {
                $query->field('id,nick_name,account');
            },
            'category' => function ($query) {
                $query->field('id,title');
            },
            'matches'  => function ($query) {
                $query->field('id,match_id,comp,home,away');
            }
        ])->where($where)
            ->page($page, $limit)
            ->order('id DESC')
            ->select();


        if (count($list) > 0) {
            $count = LiveHistoryModel::where($where)->count();

            foreach ($list as &$item) {
                $item->start_stamp_str  = $item->start_stamp > 0 ? date('Y-m-d H:i:s', $item->start_stamp) : '';
                $item->end_stamp_str    = $item->end_stamp > 0 ? date('Y-m-d H:i:s', $item->end_stamp) : '';
                $item->gift_profit      = $item->gift_profit > 0 ? bcdiv(strval($item->gift_profit), '100', 2) : 0;
                $item->other_gift_price = $item->other_gift_price > 0 ? bcdiv(strval($item->other_gift_price), '100', 2) : 0;
                $item->live_minute      = '';
                $item->avg_duration = self::avg_duration($item->liveid);

                $diff = intval($item->end_stamp - $item->start_stamp);
                if ($diff > 0) {
                    $h = floor($diff / 3600);
                    $i = floor($diff % 3600 / 60);
                    $s = floor($diff % 3600 % 60);

                    $item->live_minute = $h . '小时 ' . $i . '分 ' . $s . '秒';
                }
            }


            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function history_excel()
    {
        $anchor_id = Request::param("anchorid");
        $nick_name = Request::param("nick_name");
        $start_time = Request::param("start_time");
        $end_time = Request::param("end_time");

        $where = [];

        if ($anchor_id) {
            $where[] = ['anchorid', '=', is_numeric($anchor_id) ? $anchor_id : 0];
        }

        if (mb_strlen($nick_name) > 0) {
            $u_where[] = ['nick_name', 'like', "%{$nick_name}%"];
            $uid_arr   = UserModel::where($u_where)->column('id');
            $where[]   = ['anchorid', 'in', $uid_arr];
        }

        if ($start_time != '') {
            $start_time = strtotime($start_time);
            $where[] = ['start_stamp', '>=', $start_time];
        }

        if ($end_time != '') {
            $end_time = strtotime($end_time);
            $where[] = ['end_stamp', '<=', $end_time];
        }

        $list = LiveHistoryModel::with([
            'anchor'   => function ($query) {
                $query->field('id,nick_name,account');
            },
            'category' => function ($query) {
                $query->field('id,title');
            },
            'matches'  => function ($query) {
                $query->field('id,match_id,comp,home,away');
            }
        ])->where($where)
            // ->limit(100)   // 最大默认导出100条
            ->order('id DESC')
            ->select();


        $exports = [];

        if (count($list) > 0) {
            $count = LiveHistoryModel::where($where)->count();

            foreach ($list as &$item) {
                $item->start_stamp_str  = $item->start_stamp > 0 ? date('Y-m-d H:i:s', $item->start_stamp) : '';
                $item->end_stamp_str    = $item->end_stamp > 0 ? date('Y-m-d H:i:s', $item->end_stamp) : '';
                $item->gift_profit      = $item->gift_profit > 0 ? bcdiv(strval($item->gift_profit), '100', 2) : 0;
                $item->other_gift_price = $item->other_gift_price > 0 ? bcdiv(strval($item->other_gift_price), '100', 2) : 0;
                $item->live_minute      = '';
                $item->avg_duration = self::avg_duration($item->liveid);

                $diff = intval($item->end_stamp - $item->start_stamp);
                if ($diff > 0) {
                    $h = floor($diff / 3600);
                    $i = floor($diff % 3600 / 60);
                    $s = floor($diff % 3600 % 60);

                    $item->live_minute = $h . '小时 ' . $i . '分 ' . $s . '秒';
                }

                $exports[] = [
                    $item->id ? $item->id : 0,
                    $item->anchorid ? $item->anchorid : 0,
                    $item->anchor->nick_name ? $item->anchor->nick_name : '',
                    $item->avg_duration ? $item->avg_duration : '',
                    $item->start_stamp_str ? $item->start_stamp_str : '',
                    $item->end_stamp_str ? $item->end_stamp_str : '',
                    $item->live_minute ? $item->live_minute : '',
                    $item->title ? $item->title : '',
                    @isset($item->category->title) ? $item->category->title : '',
                    $item->open_chat_num ? $item->open_chat_num : 0,
                    $item->send_chat_num ? $item->send_chat_num : 0,
                    $item->matches ? $item->matches->comp : '',
                    $item->matches ? $item->matches->home : '',
                    $item->matches ? $item->matches->away : '',
                    $item->high_count ? $item->high_count : 0,
                    $item->viewer_count ? $item->viewer_count : 0,
                    $item->ip_total ? $item->ip_total : 0,
                ];
            }
        }

        if (empty($exports)) {
            $this->error('没有相关数据');
        }

        $file_title = ['ID', '主播ID', '主播昵称', '平均时长', '开播时间', '结束时间', '直播时长', '直播标题', '直播分类', '点击私信人数', '发起私人人数', '联赛名称', '主队名称', '客队名称', '观看峰值', '观众(登录用户)', '累计IP',];
        $file_name  = '直播历史' . date('Y年m月d日H点');

        // 记录日志
        parent::addAdminLog('导出好友邀请报表');

        return export_excel($exports, $file_title, $file_name, '好友邀请');
    }

    /**
     * 每日ip统计列表
     * @return mixed
     */
    public function totalip_list()
    {
        return $this->fetch();
    }

    public function get_totalip_list()
    {
        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");
        $page       = Request::param("page");
        $limit      = Request::param("limit");

        $where = [];
        if ($start_time) {
            $where[] = ['date', '>=', $start_time];
        }
        if ($end_time) {
            $where[] = ['date', '<=', $end_time];
        }
        $list = IpStatsModel::where($where)->page($page, $limit)->order('id', 'desc')->select();
        if (count($list) > 0) {
            $count = IpStatsModel::where($where)->count();

            foreach ($list as &$item) {
                $date_time      = strtotime($item->date) ?: 0;
                $item->date_str = $date_time > 0 ? date('Y-m-d', $date_time) : '';
            }

            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function reply_history()
    {
        return $this->fetch();
    }

    public function get_reply_history()
    {
        $title = Request::param("title");
        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");
        $page      = Request::param("page");
        $limit     = Request::param("limit");

        $where = [];
        // $where[] = ['operator', '=', 'ftp'];

        if ($start_time) {
            $where[] = ['create_time', '>=', strtotime($start_time)];
        }
        if ($end_time) {
            $where[] = ['create_time', '<=', strtotime($end_time)];
        }

        if (mb_strlen($title) > 0) {
            $where[] = ['title', 'like', "%{$title}%"];
        }

        $list = VideoModel::where($where)
            ->page($page, $limit)
            ->order('id DESC')
            ->select();

        if (count($list) > 0) {
            $configURL = rtrim(ConfigPubModel::where('id', 1)->value('video_play_url '), '/');
            foreach ($list as $key => $value) {
                if (LiveModel::where([['title', '=', $value['title']]])->count()) {
                    $list[$key]['live_status'] = 1;
                } else {
                    $list[$key]['live_status'] = 0;
                }
                if (strpos($value['play_url'], 'http') === false) {
                    // echo strpos($value['play_url'], 'http');
                    $list[$key]['down_url'] = $configURL . $value['down_url'];
                    $list[$key]['play_url'] = $configURL . $value['play_url'];
                }
                // $list[$key]['create_time'] = date("Y-m-d H:i:s", $value['create_time']);
            }
            $count = VideoModel::where($where)->count();
            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function set_skip_time()
    {
        $id = Request::param("id");
        $skip_time = Request::param("skip_time");
        if (!VideoModel::where('id', $id)->update(['skip_time' => $skip_time])) {
            return static::bulidFail('设置失败');
        }

        return static::bulidSuccess(null, '设置成功');
    }

    public function del_reply_history()
    {
        if (!ctype_digit($id = $this->post('id'))) {
            return static::bulidFail('ID错误');
        }

        if (!$model = VideoModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的视频');
        }


        $path = str_replace("/index.mp4", "", $model->down_url);
        // exec("rm -rf .".$path);
        // 远程删除
        $key = rtrim(ConfigPubModel::where('id', 1)->value('video_upload_key '), '/');
        $configURL = rtrim(ConfigPubModel::where('id', 1)->value('video_play_url '), '/');
        // $configURL = "http://127.0.0.1";
        $configURL = "https://video.mlive.plus";
        $req = $configURL . "/index/remove_file?path=." . $path . "&key=" . $key;

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $configURL . "/index/remove_file");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "path=." . $path . "&key=" . $key);

        // Receive server response ...
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $server_output = curl_exec($ch);

        curl_close($ch);
        // var_dump($server_output);
        // var_dump(file_get_contents(urldecode($req)));
        // return;
        if (!$model->delete()) {
            return static::bulidFail('删除失败');
        }

        return static::bulidSuccess(null, '删除成功');
    }

    public function replay_to_live()
    {
        $id = Request::param("id", 0);

        if ($id > 0) {
            $live_server = new LiveServer();
            $res         = $live_server->adminReplayToLive($id);
            if ($res) {
                VideoModel::where("id", $id)->update(["lived" => 1]);
                // 记录日志
                return parent::bulidSuccess("开播成功");
            }
        }

        return static::bulidFail('开播失败:' . $res);
    }

    public function activity_toggle()
    {
        $params = Request::param();
        $ab = ActivityBarrageModel::where("status", 1)->find();
        // 广播消息

        LiveModel::where("id", $params['id'])->update(["activity_toggle" => $params['activity_toggle']]);
        $live = LiveModel::get($params['id']);
        $tim = new TencentTimServer();
        if ($params['activity_toggle'] == 0) {
            $r = new ActivityBarrageStatModel();
            $r->ab_id = $ab['id'];
            $r->time = time();
            $r->liveid = $live['liveid'];

            $cache = Cache::store('redis')->handler();
            $anchorid = $live['anchorid'] * 100;
            $r->sum = count($cache->hGetAll("ACTIVITY_STAT_{$anchorid}_{$ab['id']}_{$live['liveid']}"));

            $r->save();
            $tim->CleanChatHis($live['anchorid'] * 100);
        }


        $res = $tim->ActivityBarrage($params['anchor_id'], $params['activity_toggle']);
        if ($res) {
            return parent::bulidSuccess("设置成功");
        }

        return parent::bulidSuccess('设置成功');
    }

    // 直播预告
    public function preview()
    {
        return $this->fetch();
    }

    public function preview_handle()
    {
        $params = Request::param();
        $where = [];

        if (isset($params['comp_title']) && $params['comp_title'] != '') {
            $where[] = ['comp_title', 'like', "%{$params['comp_title']}%"];
        }

        if (isset($params['sport_id']) && $params['sport_id'] != '') {
            $where[] = ['sport_id', '=', $params['sport_id']];
        }

        if (isset($params['anchor_id']) && $params['anchor_id'] != '') {
            $where[] = ['anchor_ids', 'like', "%{$params['anchor_id']}%"];
        }

        if (isset($params['nickname']) && $params['nickname'] != '') {
            $where[] = ['anchor_nicknames', 'like', "%{$params['nickname']}%"];
        }

        // 比赛时间今天以后的
        $where[] = ['match_time', '>=', strtotime(date('Y-m-d', time()))];

        $list = LivePreviewModel::where($where)->page($this->get('page', 1), $this->get('limit', 20))->order('match_time desc')->select();
        $count = LivePreviewModel::where($where)->count('*');
        foreach ($list as $key => $value) {
            $list[$key]['date'] = date("Y-m-d H:i:s", $value['match_time']);
            $list[$key]['anchors'] = '';
            $anchor_ids = explode(',', $value['anchor_ids']);
            for ($i = 0; $i < count($anchor_ids); $i++) {
                $list[$key]['anchors'] .= $anchor_ids[$i] . '-' . UserModel::get($anchor_ids[$i])['nick_name'] . ' ';
            }
        }
        if (count($list) > 0) {
            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    // 添加直播预告
    public function preview_add()
    {
        $anchors = UserModel::where([['is_anchor', '=', 1], ['status', '=', 0]])->select();
        $this->assign('anchors', $anchors);
        return $this->fetch();
    }

    // 添加直播预告
    public function preview_add_handle()
    {
        $params = Request::param();
        $anchor_ids = '';
        $anchor_nicknames = '';
        $params['anchor_id'] = array_values(array_filter($params['anchor_id']));

        if (count($params['anchor_id']) == 0) {
            return parent::bulidFail('请添加主播');
        }
        if ($params['match_id'] == '') {
            return parent::bulidFail('请选择赛事');
        }
        if (isset($params['anchor_id']) && count($params['anchor_id']) > 0) {
            $anchor_ids = implode(",", $params['anchor_id']);
            // var_dump($anchor_ids);
            for ($i = 0; $i < count($params['anchor_id']); $i++) {
                if ($params['anchor_id'][$i] != '') {
                    $anchor_nicknames .= UserModel::get($params['anchor_id'][$i])['nick_name'] . ',';
                }
            }
        }

        if ($params['sport_id'] == 1 || $params['sport_id'] == 2) {
            $match = MatchesScheduleModel::where([['match_id', '=', $params['match_id']], ['sport_id', '=', $params['sport_id']]])->find();
        } else {
            $match = MatchesScheduleModel::where([['match_id', '=', $params['match_id']]])->find();
        }

        if (isset($params['id']) && intval($params['id']) > 0) {
            $lp = LivePreviewModel::get($params['id']);
        } else {
            $lp = new LivePreviewModel();
            $lp->created_at = date('Y-m-d H:i:s', time());
        }
        $lp->match_id = $params['match_id'];
        $lp->anchor_ids = $anchor_ids;
        $lp->anchor_nicknames = $anchor_nicknames;
        $lp->sport_id = $params['sport_id'];
        $lp->comp_title_en = $match['comp_short_en'];
        $lp->comp_title = $match['comp_short_zh'];
        $lp->home = $match['home'];
        $lp->home_en = $match['home_en'];
        $lp->home_logo = $match['home_logo'];
        $lp->away = $match['away'];
        $lp->away_en = $match['away_en'];
        $lp->away_logo = $match['away_logo'];
        $lp->match_time = $match['match_time'];
        $lp->updated_at = date('Y-m-d H:i:s', time());

        if ($lp->save()) {
            return parent::bulidSuccess("保存成功");
        }

        return parent::bulidFail('保存失败');
    }

    // 编辑预告
    public function preview_edit()
    {
        $id = Request::param('id');
        $preview = LivePreviewModel::get($id);
        $anchors = UserModel::where([['is_anchor', '=', 1], ['status', '=', 0]])->select();
        $this->assign('id',  $id);
        $this->assign('anchors',  $anchors);
        $this->assign('anchor_ids', explode(",", $preview['anchor_ids']));
        $this->assign('preview', $preview);
        return $this->fetch();
    }

    public function preview_custom_add()
    {
        $anchors = UserModel::where([['is_anchor', '=', 1], ['status', '=', 0]])->select();
        $this->assign('anchors', $anchors);
        return $this->fetch();
    }

    public function preview_custom_add_handle()
    {
        $params = Request::param();
        $anchor_ids = '';
        $anchor_nicknames = '';
        $params['anchor_id'] = array_values(array_filter($params['anchor_id']));

        if (count($params['anchor_id']) == 0) {
            return parent::bulidFail('请添加主播');
        }
        if (isset($params['anchor_id']) && count($params['anchor_id']) > 0) {
            $anchor_ids = implode(",", $params['anchor_id']);
            // var_dump($anchor_ids);
            for ($i = 0; $i < count($params['anchor_id']); $i++) {
                if ($params['anchor_id'][$i] != '') {
                    $anchor_nicknames .= UserModel::get($params['anchor_id'][$i])['nick_name'] . ',';
                }
            }
        }
        if (isset($params['id']) && intval($params['id']) > 0) {
            $lp = LivePreviewModel::get($params['id']);
        } else {
            $lp = new LivePreviewModel();
            $lp->created_at = date('Y-m-d H:i:s', time());
        }
        $lp->anchor_ids = $anchor_ids;
        $lp->anchor_nicknames = $anchor_nicknames;
        $lp->sport_id = $params['sport_id'];
        $lp->comp_title = $params['comp_title'];
        $lp->home = $params['home'];
        $lp->home_logo = $params['home_logo'];
        $lp->away = $params['away'];
        $lp->away_logo = $params['away_logo'];
        $lp->match_time = strtotime($params['start_time']);
        $lp->updated_at = date('Y-m-d H:i:s', time());
        $lp->is_custom = 1;
        if ($lp->save()) {
            return parent::bulidSuccess("保存成功");
        }

        return parent::bulidFail('保存失败');
    }

    public function preview_custom_edit()
    {
        $id = Request::param('id');
        $preview = LivePreviewModel::get($id);
        $preview['start_time'] = date("Y-m-d H:i:s", $preview['match_time']);
        $anchors = UserModel::where([['is_anchor', '=', 1], ['status', '=', 0]])->select();
        $this->assign('id',  $id);
        $this->assign('anchors',  $anchors);
        $this->assign('anchor_ids', explode(",", $preview['anchor_ids']));
        $this->assign('preview', $preview);
        return $this->fetch();
    }

    public function preview_custom_edit_handle()
    {
    }

    // 直播预告删除
    public function preview_del()
    {
        $id = Request::param('id');

        if (!LivePreviewModel::where("id", $id)->delete()) {
            return static::bulidFail('删除失败');
        }

        return static::bulidSuccess(null, '删除成功');
    }

    // 渠道观众数量
    public function viewer_source_count()
    {
        $data = $this->get_source_count();

        return view("viewer_source_count", [
            "data" => $data->viewer_source_count,
            "sum" => $data->sum,
        ]);
    }

    public function get_source_count() {
        // 渠道统计
        $viewer_source_count = [];
        $sum = 0;
        $redis = Cache::store('redis')->handler();
        // 当前日期
        $date = date("Y-m-d");

        // 获取当天的所有渠道号集合的 key
        $channel_stat_key = "live_watch_channel_stat_v2:{$date}";

        // 查询所有渠道号
        $channels = $redis->smembers($channel_stat_key);

        if ($channels) {
            // 查询数据库获取渠道名称
            $list = RegSourceModel::where('source_key', 'in', $channels)->select();
            $channelNames = [];
            foreach ($list as $item) {
                $channelNames[$item['source_key']] = $item['source_name'];
            }
    
            foreach ($channels as $channel) {
                // 构建每个渠道对应的 IP 集合 key
                $channel_ip_key = "live_watch_channel_stat_v2:{$channel}:{$date}";
    
                // 获取当前渠道的唯一 IP 数
                $active_user_count = $redis->scard($channel_ip_key);
    
                if ($active_user_count > 0) {
                    $source_count = [
                        'source_key' => $channel,
                        'source_name' => $channelNames[$channel] ?? $channel, // 使用数据库查询的渠道名称
                        'count' => $active_user_count,
                    ];
    
                    $viewer_source_count[] = $source_count;
                    $sum += $active_user_count;
                }
            }
    
            // 按 active_user_count 倒序排序
            usort($viewer_source_count, function ($a, $b) {
                return $b['count'] <=> $a['count'];
            });
        }
        $data = new stdClass();
        $data->viewer_source_count = $viewer_source_count;
        $data->sum = $sum;
        return $data;
    }
}
